package cn.wolfcode.web.controller;

import cn.wolfcode.common.constants.CommonConstants;
import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.common.exception.BusinessException;
import cn.wolfcode.common.web.CommonCodeMsg;
import cn.wolfcode.common.web.Result;
import cn.wolfcode.common.web.anno.RequireLogin;
import cn.wolfcode.domain.OrderInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.mq.BusinessSendCallback;
import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMessage;
import cn.wolfcode.redis.CommonRedisKey;
import cn.wolfcode.redis.SeckillRedisKey;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.util.DateUtil;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;


@RestController
@RequestMapping("/order")
@Slf4j
public class OrderInfoController {
    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private IOrderInfoService orderInfoService;

    private static ConcurrentHashMap<Long, Boolean> PRODUCT_STOCK_MAP = new ConcurrentHashMap<>();

    public static void removeOverMap(Long seckillId) {
        Boolean remove = PRODUCT_STOCK_MAP.remove(seckillId);
        log.info("[本地标识] 删除本地标识: seckillId={}, 结果: {}", seckillId, remove);
    }


    @RequireLogin
    @RequestMapping("/doSeckill")
    public Result<String> doSeckill(Integer time, Long seckillId, @RequestHeader(CommonConstants.TOKEN_NAME) String token) {
        String redisKey = "";
        UserInfo userInfo = null;
        // 使用JVM内存标记, 减少Redis的访问
        if (Boolean.TRUE.equals(PRODUCT_STOCK_MAP.get(seckillId))) {
            throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
        }
        // 1. 基于 token 获取到用户信息(必须登录)
        userInfo = this.getUserByToken(token);
        // 2. 基于场次+秒杀id获取到秒杀商品对象
        try {
            SeckillProductVo vo = seckillProductService.selectByIdAndTime(seckillId, time);
            if (vo == null) {
                throw new BusinessException(SeckillCodeMsg.REMOTE_DATA_ERROR);
            }
            // 3. 判断时间是否大于开始时间 && 小于 开始时间+2小时
        /*if (!DateUtil.isLegalTime(vo.getStartDate(), time)) {
            throw new BusinessException(SeckillCodeMsg.OUT_OF_SECKILL_TIME_ERROR);
        }*/
            // 4. 判断用户是否重复下单
            // 基于用户 + 秒杀 id + 场次查询订单, 如果存在订单, 说明用户已经下过单
            redisKey = SeckillRedisKey.SECKILL_ORDER_HASH.join(seckillId + ""); //将秒杀商品id作为key
            Long increment = redisTemplate.opsForHash().increment(redisKey, userInfo.getPhone() + "", 1);
            if (increment > 2) {
                throw new BusinessException(SeckillCodeMsg.REPEAT_SECKILL);
            }
            // 5. 判断库存是否充足
            String realCountKey = SeckillRedisKey.SECKILL_REAL_COUNT_HASH.join(time + "");
            // 扣减库存以后, 库存小于0, 说明库存不足
            Long remainStockCount = redisTemplate.opsForHash().increment(realCountKey, seckillId + "", -1);
            if (remainStockCount < 0) {
                // 说明库存不足
                PRODUCT_STOCK_MAP.put(seckillId, true);
                throw new BusinessException(SeckillCodeMsg.SECKILL_STOCK_OVER);
            }
            // 6. 执行下单操作(减少库存, 创建订单)
            //  orderNo = orderInfoService.doSeckill(userInfo, vo);
            OrderMessage orderMessage = new OrderMessage(time,seckillId,token,userInfo.getPhone());
            SendResult sendResult = rocketMQTemplate.syncSend(MQConstant.ORDER_PENDING_TOPIC, orderMessage);
            log.info(" [发送消息到MQ]  结果状态: {}", sendResult.getSendStatus());
        } catch (BusinessException e) {
            log.error("[秒杀失败] 失败原因: {}", e.getCodeMsg().getMsg());
            if (e.getCodeMsg() == SeckillCodeMsg.SECKILL_STOCK_OVER) {
                redisTemplate.opsForHash().increment(redisKey, userInfo.getPhone() + "", -1);
            }
           throw e;
        }
     return   Result.success("正在下单中, 请稍后查看订单状态");

    }

    private UserInfo getUserByToken(String token) {
        return JSON.parseObject(redisTemplate.opsForValue().get(CommonRedisKey.USER_TOKEN.getRealKey(token)), UserInfo.class);
    }


    @RequireLogin
    @RequestMapping("/find")
    public Result<OrderInfo> queryOrder(String orderNo,@RequestHeader(CommonConstants.TOKEN_NAME) String token) {
        UserInfo userInfo = this.getUserByToken(token);
        OrderInfo orderInfo = orderInfoService.selectByOrderNoRedis(orderNo,userInfo.getPhone());
        return Result.success(orderInfo);
    }
}
